package com.luoc.base.config.mybatis.controller;


import com.luoc.base.config.mybatis.entity.SysUser;
import com.luoc.base.config.mybatis.service.ISysUserRoleService;
import com.luoc.base.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author luoc
 * @since 2019-07-25
 */
@RestController
@RequestMapping("/mybatis/sys-user")
@Slf4j
public class SysUserController {

    @Autowired
    private ISysUserRoleService iSysUserRoleService;

    @PostMapping("/login")
    public Result login(@RequestBody SysUser sysUser) {
        String userName = sysUser.getUserName();
        String passWord = sysUser.getPassWord();

        // 1.获取Subjet
        Subject subject = SecurityUtils.getSubject();
        // 2. 封装用户数据
        UsernamePasswordToken token =
                new UsernamePasswordToken(userName, passWord);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            log.error("userName:{}", userName);
            return Result.error("用户姓名不存在");
        } catch (IncorrectCredentialsException e) {
            return Result.error("密码错误");
        }
        return Result.ok("登陆成功");
    }

    @GetMapping("/test")
    public Result testInjectionNull(@RequestParam String userName) {
        return Result.ok(iSysUserRoleService.selectRoleIdsByUserId(userName));
    }

    @GetMapping("/logout")
    public Result logOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok("success");
    }
}

